<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/popup.css" />

<script type="text/javascript" src="js/jquery-combined.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.sortable.min.js"></script>
<script type="text/javascript" src="js/common.js"></script>
<script type="text/javascript" src="js/sabconnect.js"></script>



<style>
    #active {font-size:18px; font-weight:bold;}
    #controls img {cursor:pointer;}
    h3 {margin-bottom:3px;}
</style>

<script type="text/javascript">

var bg = chrome.extension.getBackgroundPage();
var active_daemon = bg.active_daemon;


$(document).ready(function(){
    $('#active').html(active_daemon.label);

    $('#toolbar img').live('click',function(){
        switch($(this).attr('id')){
            case 'web':     chrome.tabs.create({url:SABConnect.daemon_url(active_daemon)}); break;
            case 'gear':    chrome.tabs.create({url:chrome.extension.getURL('settings.html')}); break;
            case 'toggle':  break;  
            default:
        }
    });

//    <span id="sab-status"></span><br />

    //console.log(bg.last_queueinfo);
    reDrawPopup();
    
    /*
    SABConnect.info({daemon:active_daemon,success:
        function(data) {
            $('#active').css({color:'green'});
        },error:function(errMsg) {
            $('#active').css({color:'red'});
        }
    });
    */
});


/*
function togglePause() {
    if(paused) {
        var mode = 'resume';
        var wasPaused = 1;
    } else {
        var mode = 'pause';
        var wasPaused = 0;
    }

}

function func1() {

    if(paused) {
        var playImg = chrome.extension.getURL('images/control_play.png');
        var img = '<img src="' + playImg +'" />';
        var msg = 'Resume Queue';
    } else {
        var pauseImg = chrome.extension.getURL('images/control_pause.png');
        var img = '<img src="' + pauseImg +'" />';
        var msg = 'Pause Queue';
    }
    $('.menu').prepend('<hr /><div id="togglePause">' + msg + '</div>');
    $('#togglePause').click(function() {
        togglePause();

    });
    // Main function of this html page
    // Add a load of html using javascript ie sabnzbd queue and details, errors, ect
//    reDrawPopup();
//    startTimer();
    
}
*/



function getSortItemPos(id) {
    
    var list = $('ul#sab-queue').sortable('toArray');
    var pos = -1;
    
    $.each(list, function(i, item) {
        if(item == id) {
            pos = i;
        }
    });
    
    return pos;
}

function reDrawPopup() {
	$('#togglePause').show();
	
    // If we do not want to redraw (such as in the middle of a drag and drop event, then skip
    //if(getPref('skip_redraw')) return;

    // Grab the errors (should be an array)
    /*var errors = getPref('errors');
    $.each(errors, function(i, error) {
        data['slot'] = slot;
        $('#errors').jqote(data).appendTo($('#sab-errors'));
    });*/
    var error = getPref('error');
    if(error) {
        $('#sab-errors').html('<div id="errors-container">' + error + '</div>');
    } else {
        // No errors, remove anything that could have been here
        // If the refresh rate is too low, will cause no errors to be ever seen
        $('#sab-errors').html('');
    }

    
    // Make sure the current queue is clear
    $('ul#sab-queue').html('');


    var data = bg.last_queueinfo;
    console.log('reDrawPopup:');
    console.log(data);

    paused   = data.paused;

    
    var fields = ['status', 'paused', 'timeleft', 'speed', 'sizeleft', 'paused_jobs'];
    
    $.each(fields, function(i, field) {
        var value = data[field];
        $('#sab-' + field).html(value);
    });
    
    var status = data.status;
    $('#sab-status').addClass(status);
    
    var slot_data = {
        'playImg':chrome.extension.getURL('images/control_play.png'),
        'pauseImg':chrome.extension.getURL('images/control_pause.png'),
        'deleteImg':chrome.extension.getURL('images/messagebox_critical.png')
    };

    console.log(data.slots);

    // Grab a list of jobs (array of slot objects from the json API)
    var jobs = data.slots;
    $.each(jobs, function(i, slot) {
        slot_data.slot = slot;
        $('#template').jqote(slot_data).appendTo($('#sab-queue'));
    });
    
    

    // The controls are low transparency until the user hovers over the parent item
    $(".item").hover(
        function () {
            // Restore opacity to full
            $(this).find('.lowOpacity').addClass('fullOpacity').removeClass('lowOpacity');
        }, 
        function () {
            // Set opacity to 20%
            $(this).find('.fullOpacity').addClass('lowOpacity').removeClass('fullOpacity');
        }
    );
    /*
    // The controls are low transparency until the user hovers over the parent item
    $(".filename").hover(
        function () {
            // Restore opacity to full
            $(this).closest('li').addClass('highlight')
        }, 
        function () {
            // Set opacity to 20%
            $(this).closest('li').removeClass('highlight')
        }
    );   */ 
    // The controls are low transparency until the user hovers over the parent item
    $(".item").hover(
        function () {
            // Restore opacity to full
            $(this).addClass('highlight');
        }, 
        function () {
            // Set opacity to 20%
            $(this).removeClass('highlight');
        }
    );
    
    // Make the ul sortable (only in the y axis)
    $("ul#sab-queue").sortable({ axis: 'y' });
    $("ul#sab-queue").disableSelection();
    
    // Cache the position when we start sorting
    $('ul#sab-queue').bind('sortstart', function(event, ui) {
        // Skip queue redrawing for the duration of the sort
        setPref('skip_redraw', 1);
        var id = $(ui.item).attr('id');
        oldPos = getSortItemPos(id);
    });
    
    // When the sorting has finished, do a SABnzbd api call
    $('ul#sab-queue').bind('sortstop', function(event, ui) {
        setPref('skip_redraw', 0);
        var id = $(ui.item).attr('id');
        var pos = getSortItemPos(id);
        // Make sure it has actually moved position
        if(pos == oldPos) return;
        // Position has moved, send off a SABnzbd api call
        moveQueueItem(id, pos);
    });
    
    // Do these need to be .live()?
    $('.resumeItem').click(function() {
        var id = $(this).closest('li.item').attr('id');
        queueItemAction('resume', id, reDrawPopup);
        
        return false;
    });
    
    $('.pauseItem').click(function() {
        var id = $(this).closest('li.item').attr('id');
        queueItemAction('pause', id, reDrawPopup);
        
        return false;
    });    
    
    $('.deleteItem').click(function() {
        var li = $(this).closest('li.item');
        var id = li.attr('id');
        // Delete the li element (mainly for user feedback). If they choose to open the popup again
        // before the delete and redraw have taken place the item will show. Really needs removing from 'queue' object (preference)
        li.remove();
        queueItemAction('delete', id, reDrawPopup);
        
        return false;
    });
    
/*
    if(getPref('show_graph')) {
        var api = new jGCharts.Api();
        var url = api.make({
            data : getPref('speedlog'), //MANDATORY
            type : 'lc',
            fillarea : true, //default false
            fillbottom : true, //default false
            size : '220x75'
        })
        
        $('#graph').html('<div id="graph-inner"><img src="' + url + '" /></div>');
    }
*/
    
}

$(document).ready(function(){
   var daemons = getPref('daemons');
   $.each(daemons, function(i, daemon) {
     $('#display-daemon').jqote({'daemon':daemon}).appendTo($('#daemons'));
   });
   
   $('#daemons').sortable({ axis:'y' })
});


chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
        console.log(sender.tab ?
            "from a content script:" + sender.tab.url :
            "from the extension");
        if (request.greeting == "hello")
            sendResponse({farewell: "goodbye"});
        else
            sendResponse({}); // snub them.
});



</script>

<script type="text/html" id="template">
<![CDATA[
<li id="<%= this.slot.nzo_id %>" class="item">
    <div class="file-<%= this.slot.status %> filename"><%= this.slot.filename %></div>
    
    <div class="controls">
        <% if ( this.slot.status == "Paused" ) { %>
            <a class="resumeItem lowOpacity" href=""><img src="<%= this.playImg %>" /></a>
        <% } else { %>
            <a class="pauseItem lowOpacity" href=""><img src="<%= this.pauseImg %>" /></a>
        <% } %>
        <a class="deleteItem lowOpacity" href=""><img src="<%= this.deleteImg %>" /></a>
    </div>
    
    <div class="float-fix"></div>
    <% if ( this.slot.percentage != "0" ) { %>
    <div class="progressBarContainer">
        <div class="progressBarInner" style="width:<%= this.slot.percentage %>%"></div>
    </div>
    <% } %>

</li>
]]>
</script>

<script type="text/html" id="errors">
<![CDATA[
<li class="error">
    <%= this.error %>
</li>
]]>
</script>

<script type="text/html" id="display-daemon">
<![CDATA[
<li class="daemon">
  <%= this.daemon.label %>
</li>
]]>
</script>

</head>
<body>

<div id="toolbar">
    <img id="gear" alt="" src=""/>
    <img id="web" alt="" src=""/>
    <img id="toggle" alt="" src=""/>
</div>

<h3 id="active"></h3>
<div id="sabInfo">

    <div id="sab-errors"></div>

    <div class="col-left">
        <span id="sab-status"></span><br />
        <div id="sab-timeleft"></div>
    </div>

    <div class="col-right">
        <div id="sab-speed"></div>
        <span id="sab-sizeleft"></span>
    </div>
    <div class="float-fix"></div>
    
    <div id="graph"></div>
    
    <ul id="sab-queue"></ul>
 

</div>

<!--
<h3>Daemons</h3>
<div id='daemons'>
	
</div>
-->

</body>
</html>
